<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\WebPage;
use StudyBuddy\Paginator;
use StudyBuddy\Template\Urhere;

class Viewresources extends WebPage {

    protected $pagerPath = '/resources';

    /**
     * Indicates the current tab
     *
     * @var string
     */
    protected $qtab = 'resources';

    /**
     * Object MongoCursor
     * @var Object MongoCursor
     */
    protected $oCursor = null;
    protected $catID = 0;
    protected $levelID = 0;
    protected $subjectID = 0;
    protected $pageID = 1;
    protected $title = '';
    protected $pageHead = '';
    protected $aTplVars = array();

    /**
     * Indicates the number of matched items like
     *
     * @var int
     */
    protected $count;
    protected $PER_PAGE = 20;

    /**
     * Pagination links on the page
     * will not be handled by Ajax
     *
     * @var bool
     */
    protected $notAjaxPaginatable = true;

    protected function main() {

        $this->pageID = (int) $this->oRequest->get('pageID', 'i', 1);
        $this->catID = (int) $this->oRequest->get('catID', 'i', 0);
        $this->levelID = (int) $this->oRequest->get('levelID', 'i', 0);
        $this->subjectID = (int) $this->oRequest->get('subjectID', 'i', 0);

        $this->getCursor()
                ->paginate()
                ->sendCacheHeaders();

        $this->aPageVars['title'] = $this->title;
        $this->makeTopTabs()
                ->makeFilterrtab()
                ->makeRListHeader()
                ->makeRlistBody()
                ->makeFollowedTags()
                ->makeRecentActivites()
                ->makeRecentTags()
                ->makeTutorListing();
    }

    /**
     * Select items according to conditions passed in GET
     * Conditions can be == 'unanswered', 'hot', 'recent' (default)
     */
    protected function getCursor() {
        $this->PER_PAGE = $this->oRegistry->Ini->PER_PAGE_QUESTIONS;

        //$aFields = array();

        $where = array();
        /**
         * Default sort is by timestamp Descending
         * meaning most recent should be on top
         *
         */
        $sort = array('i_reg_ts' => -1);

        $this->title = $this->_('All resources');

        if ($this->catID > 0) {
            $aCat = array(
                1 => 'Note and Mindmaps',
                2 => 'Textbook	solutions',
                3 => 'Exam	papers Solutions',
                4 => 'Suggested Study schedule',
                5 => 'Study Checklist',
                6 => 'Coming Soon'
            );
            $aLevel = array(
                1 => 'P1',
                2 => 'P2',
                3 => 'P3',
                4 => 'P4',
                5 => 'P5',
                6 => 'P6',
                7 => 'S1',
                8 => 'S2',
                9 => 'S3&S4'
            );
            $aSubject = array(
                1 => 'E Maths',
                2 => 'A Maths',
                3 => 'Physics'
            );

            $this->title = $this->_('All resources in category ' . $aCat[$this->catID]);
            $where['category'] = "$this->catID";
            //
            if ($this->levelID > 0) {
                if ($this->subjectID > 0) {
                    $this->title = $this->_('All resources in category ' . $aCat[$this->catID] . 'and level ' . $aLevel[$this->levelID] . 'and subject ' . $aSubject[$this->subjectID]);
                } else {
                    $this->title = $this->_('All resources in category ' . $aCat[$this->catID] . 'and level ' . $aLevel[$this->levelID]);
                }
                $where['level'] = "$this->levelID";
            }
            if ($this->subjectID > 0) {
                if ($this->levelID > 0) {
                    $this->title = $this->_('All resources in category ' . $aCat[$this->catID] . 'and level ' . $aLevel[$this->levelID] . 'and subject ' . $aSubject[$this->subjectID]);
                } else {
                    $this->title = $this->_('All resources in category ' . $aCat[$this->catID] . 'and subject ' . $aSubject[$this->subjectID]);
                }
                $where['subject'] = "$this->subjectID";
            }
        }

        /**
         * @todo for effecienty explicitely specify which
         * doc fields to select or at least tell
         * which NOT to select, for example we don't need
         * a_edited and a_title
         *
         */
        $this->oCursor = $this->oRegistry->Mongo->RESOURCE_DOCS->find($where);
        d('$this->oCursor: ' . gettype($this->oCursor));
        $this->oCursor->sort($sort);

        return $this;
    }

    /**
     * Create a paginator object
     * and paginate results of select
     *
     * @return object $this
     */
    protected function paginate() {
        $path = '/cat' . $this->catID . '/level' . $this->levelID . '/subject' . $this->subjectID;

        if ($this->catID == 0 && $this->levelID == 0 && $this->subjectID == 0) {
            $path = '';
        }

        d('paginating with $this->pagerPath: ' . $this->pagerPath);
        $oPaginator = Paginator::factory($this->oRegistry);
        $oPaginator->paginate($this->oCursor, $this->PER_PAGE, array('path' => $this->pagerPath . $path));

        $this->pagerLinks = $oPaginator->getLinks();

        d('$this->pagerLinks: ' . $this->pagerLinks);

        return $this;
    }

    /**
     * Generates html of the "recent tags"
     * block
     *
     * If user is logged in AND
     * has 'followed tags' then don't use
     * cache and instead do this:
     * get array of recent tags, sort in a way
     * than user's tags are on top and then render
     * This way user's tags will always be on top
     * at a cost of couple of milliseconds we get
     * a nice personalization that does increase
     * the click rate!
     *
     * @return object $this
     */
    protected function makeRecentTags() {

        $aUserTags = $this->oRegistry->Viewer['a_f_t'];
        if (!empty($aUserTags)) {
            $s = $this->getSortedRecentTags($aUserTags);
        } else {
            $s = $this->oRegistry->Cache->get('qrecent');
        }

        $tags = \tplBoxrecent::parse(array('tags' => $s, 'title' => $this->_('Recent Tags')));
        d('cp');
        $this->aPageVars['tags'] = $tags;

        return $this;
    }

    //hoangto tutor listing
    protected function makeTutorListing() {

        $s = $this->getSortedTutors();
        $tutors = \tplTutorBox::parse(array('tutors' => $s, 'title' => $this->_('Tutor Listing')));
        d('cp');
        $this->aPageVars['tutors'] = $tutors;

        return $this;
    }

    //hoangto tutor listing
    protected function makeRecentActivites() {

        $s = $this->getSortedActivities();
        $tutors = \tplActivityBox::parse(array('ractivites' => $s, 'title' => $this->_('Recent activities')));
        d('cp');
        $this->aPageVars['activities'] = $tutors;

        return $this;
    }

    /**
     * @todo finish this
     *
     * Must peek at last item in cursor and get
     * its' timestamp, then rewind cursor back
     * Use usual uid, usergroup, pageID, lang for etag
     * maybe also use reputation score now
     */
    protected function sendCacheHeaders() {

        return $this;
    }

    protected function makeTopTabs() {
        $guest = null;
        if($this->oRegistry->Viewer->isGuest()) {
            $guest['link_ask'] = '#'; // 13
            $guest['link_ask_click'] = ' onclick="oSL.getQuickRegForm()"'; //14
        }
        $tabs = Urhere::factory($this->oRegistry)->get('tplToptabs', $this->qtab, $guest);
        $this->aPageVars['topTabs'] = $tabs;

        return $this;
    }

    protected function makeFilterrtab() {

        $filterTab = \tplFiltertabr::parse(array('level' => $this->buildLevel(), 'subject' => $this->buildSubject(), 'catID' => $this->catID, 'levelID' => $this->levelID, 'subjectID' => $this->subjectID));
        $this->aPageVars['filterTabs'] = $filterTab;

        return $this;
    }

    protected function makeRlistHeader() {

        $this->aPageVars['qheader'] = '<h1>' . $this->title . '</h1>';

        return $this;
    }

    protected function makeRlistBody() {

        $uid = $this->oRegistry->Viewer->getUid();

        $isAdmin = $this->oRegistry->Viewer->isAdmin();

        $func = function(&$a) use($uid, $isAdmin) {
                    $a['is_admin'] = $isAdmin;
                };

        $sRdivs = \tplRrecent::loop($this->oCursor, true, $func);

        $sRlist = \tplRlist::parse(array($sRdivs, $this->pagerLinks, $this->notAjaxPaginatable), false);
        $this->aPageVars['body'] = $sRlist;
        d('cp');
        /**
         * In case of Ajax can just send out sQlist as result
         */
        return $this;
    }

    /**
     * Creates div with tags user follows
     * The values from the tag links in that div
     * are also used by Javascript to highlight
     * the divs with questions that contain these tags
     *
     * This block is only added if user follows
     * at least one tag
     *
     * @return object $this
     */
    protected function makeFollowedTags() {

        $aFollowed = $this->oRegistry->Viewer['a_f_t'];
        d('$aFollowed: ' . print_r($aFollowed, 1));
        if (!empty($aFollowed)) {

            $this->aPageVars['side'] = '<div id="usrtags" class="fl cb w90 pl10 mb10"><div class="pad8 lg cb fr rounded3 w90"><h4>' .
                    $this->_('Tags you follow') . '</h4>' .
                    \tplFollowedTags::loop($aFollowed, false) . '</div></div>';
        }

        return $this;
    }

    /**
     * Creates html for the recent tags block
     * but user's followed tags will always be
     * on top
     *
     *
     * @param array $aUserTags array of tags user follows
     *
     * @return string html with parsed tags links
     */
    protected function getSortedRecentTags(array $aUserTags, $type = 'recent') {

        $limit = 9;
        if ('unanswered' === $type) {
            //$cur = $this->oRegistry->Mongo->UNANSWERED_TAGS->find(array(), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
            $cur = $this->oRegistry->Mongo->UNANSWERED_TAGS->find(array(), array('tag', 'i_count'))->sort(array('i_count' => -1))->limit($limit);
        } else {
            //$cur = $this->oRegistry->Mongo->QUESTION_TAGS->find(array('i_count' => array('$gt' => 0)), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
            $cur = $this->oRegistry->Mongo->QUESTION_TAGS->find(array('i_count' => array('$gt' => 0)), array('tag', 'i_count'))->sort(array('i_count' => -1))->limit($limit);
        }

        d('got ' . $cur->count(true) . ' tag results');
        $aTags = iterator_to_array($cur);

        d('aTags: ' . print_r($aTags, 1));

        if (!empty($aTags)) {
            usort($aTags, function($a, $b) use ($aUserTags) {
                        return (in_array($a['tag'], $aUserTags)) ? -1 : 1;
                    });
        };

        d('$aTags now: ' . print_r($aTags, 1));
        $html = ('unanswered' === $type) ? \tplUnanstags::loop($aTags) : \tplLinktag::loop($aTags);

        d('html recent tags: ' . $html);

        return '<div class="tag"><ul>' . $html . '</ul></div>';
    }

    //hoangto tutor listing loop
    protected function getSortedTutors() {

        $cur = $this->oRegistry->Mongo->USERS->find(array('tmp_role' => 'tutor'))->sort(array('experience' => -1))->limit(9);

        $canTeach = '';

        $func = function(&$a) use($canTeach) {
                    $a['canTeach'] = $canTeach;
                };

        $tutors = \tplTutorListing::loop($cur, true, $func);

        return $tutors;
    }

    //hoangto tutor listing loop
    protected function getSortedActivities() {

        $act_link = '';
        $badges = '';

        $func = function(&$a) use($act_link, $badges) {
                    $a['act_link'] = $act_link;
                    $a['badges'] = $badges;
                };

        $cur = $this->oRegistry->Mongo->ACTIVITIES->find()->sort(array('i_ts' => -1))->limit(5);

        $tutors = \tplActivityList::loop($cur, true, $func);

        return $tutors;
    }

    protected function buildSubject() {
        $s = '';
        $current = $this->subjectID;
        $subject = array(
            1 => 'E Maths',
            2 => 'A Maths',
            3 => 'Physics'
        );

        $tpl = '<option value="%1$s"%2$s>%3$s</option>';
        foreach ($subject as $key => $val) {
            $selected = ($key == $current) ? ' selected="selected"' : '';
            $s .= vsprintf($tpl, array($key, $selected, $val));
        }

        return $s;
    }

    protected function buildLevel() {
        $s = '';
        $current = $this->levelID;
        $level = array(
            1 => 'P1',
            2 => 'P2',
            3 => 'P3',
            4 => 'P4',
            5 => 'P5',
            6 => 'P6',
            7 => 'S1',
            8 => 'S2',
            9 => 'S3&S4'
        );

        $tpl = '<option value="%1$s"%2$s>%3$s</option>';
        foreach ($level as $key => $val) {
            $selected = ($key == $current) ? ' selected="selected"' : '';
            $s .= vsprintf($tpl, array($key, $selected, $val));
        }

        return $s;
    }

}
